package cn.com.lyj6851.auth.config;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.csrf.CsrfFilter;
import org.springframework.web.filter.CharacterEncodingFilter;

import cn.com.lyj6851.auth.authentication.MyLogoutSuccessHandler;
import cn.com.lyj6851.common.config.FormAuthenticationConfig;
/**
 * 3.1、@EnableGlobalMethodSecurity(securedEnabled=true) 开启@Secured 注解过滤权限
 * 3.2、@EnableGlobalMethodSecurity(jsr250Enabled=true)开启@RolesAllowed 注解过滤权限
 * 3.3、@EnableGlobalMethodSecurity(prePostEnabled=true) 使用表达式方法级别的安全性
 * 
 * @PreAuthorize 在方法调用之前,基于表达式的计算结果来限制对方法的访问
 * @PostAuthorize 允许方法调用,但是如果表达式计算结果为false,将抛出一个安全性异常
 * @PostFilter 允许方法调用,但必须按照表达式来过滤方法的结果
 * @PreFilter 允许方法调用,但必须在进入方法之前过滤输入值
 * 
 * @PreAuthorize("hasRole(‘admin‘)")
 * @RequestMapping(value = "/user/", method = RequestMethod.GET)
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter{

	@Autowired
    private UserDetailsService userDetailsService;
    
    @Autowired
    private FormAuthenticationConfig formAuthenticationConfig;
    
    @Autowired
    private LogoutSuccessHandler logoutSuccessHandler;

    
	@Bean
    public PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

	 /**
     * 配置授权的用户信息
     *
     * @param authenticationManagerBuilder
     * @throws Exception
     */
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
		//auth.parentAuthenticationManager(authenticationManagerBean());
	}

	@Bean
	@ConditionalOnMissingBean(LogoutSuccessHandler.class)
	public LogoutSuccessHandler logoutSuccessHandler() {
	    MyLogoutSuccessHandler myLogoutSuccessHandler = new MyLogoutSuccessHandler();
	    //myLogoutSuccessHandler.setSecurityProperties(securityProperties);
	    return myLogoutSuccessHandler;
	}
	
	@Override
	@Bean
	protected AuthenticationManager authenticationManager() throws Exception {
		return super.authenticationManager();
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		CharacterEncodingFilter filter = new CharacterEncodingFilter();
        filter.setEncoding("UTF-8");
        filter.setForceEncoding(true);
        http.addFilterBefore(filter,CsrfFilter.class);

		
		// 表单登录配置项
        formAuthenticationConfig.configure(http);
		// TODO Auto-generated method stub
		http
			.authorizeRequests()
			.antMatchers("/authentication/require",
	                "/authentication/form",
	                "/login",
	                "/error",
	                "/code/*",
	                "/**/*.js",
                    "/**/*.css",
                    "/**/*.jpg",
                    "/**/*.png",
                    "/**/*.woff2"
	        		).permitAll()
			.and()
			.logout()
				.logoutUrl("/signOut")
				.logoutSuccessHandler(logoutSuccessHandler)
                .deleteCookies("JSESSIONID")
                .and()
                .authorizeRequests()
	        .anyRequest().authenticated()
	        .and()
	        .exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler())
	        .and().csrf().disable();
	}
	
	
	
}
